iT邦幫忙

2025 iThome 鐵人賽

DAY 3
0

昨天成功把題庫處理好了,今天做一個簡單的搜尋頁面來試試看。考慮到之後要整合AI,我選擇使用Flask框架來製作,工具選用visual studio。
這裡選的是帶jinja範本的專案,範本會幫我們準備好一些需要的檔案,操作起來更方便一點。
https://ithelp.ithome.com.tw/upload/images/20250917/201693706gOTt5vV9N.png
建立好後,會看到範本幫我們創建了下面幾個資料夾和檔案,如果是空白專案,可以參考 Flask Web 框架教學來手動新增。

project_name
├─ project_name
|   ├─ static      # 存放css、js檔、圖片等
|   ├─ templates   # 存放html檔
|   ├─ __init__.py
|   └─ views.py
└─ runserver.py

▍程式碼

  1. 函式search用來接收前端的搜尋內容,再從題庫裡找到對應的資料
# views.py

# 確保檔案能被讀取
json_path = os.path.join(" 處理好的json檔路徑 ")
try:
    with open(json_path, 'r', encoding='utf-8-sig') as f:
        KNOWLEDGE_BASE = json.load(f)
    print("成功載入。")
except FileNotFoundError:
    print(f"錯誤: 找不到檔案於 {json_path}")
    KNOWLEDGE_BASE = []
except json.JSONDecodeError as e:
    print(f"解析 JSON 檔案時發生錯誤: {e}")
    KNOWLEDGE_BASE = []

@app.route('/search')
def search():
    query = request.args.get('q', '').lower()

    if query:
        search_results = []
        for item in KNOWLEDGE_BASE:
            # 題目或答案包含關鍵字就加入結果
            if (
                ("題目" in item and query in item["題目"].lower()) or
                ("答案" in item and query in item["答案"].lower())
            ):
                # 將需要顯示的項目加到結果列表
                search_results.append({
                    "question_text": item.get("題目", ""),
                    "options": item.get("選項", []),
                })
    else:
        search_results = []

    return render_template(
        'index.html',
        title='搜尋結果',
        results=search_results,
        search_query=query
    )

  1. 準備一個頁面來輸入,顯示搜尋結果
<!-- index.html -->

<main>
    <!-- 搜尋框 -->
    <div>
        <div>
            <form method="GET" action="/search">
                <div>
                    <input type="text" name="q" placeholder="請輸入關鍵字搜尋...">
                    <div>
                        <button type="submit">搜尋</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 搜尋結果區域 -->
    <div>
        <div >
            <h4>搜尋結果</h4>
            <div id="search-results">
                <!-- 如果有找到關鍵字相關題目,依序印出題目選項 -->
                {% if results %}
                {% for result in results %}
                <div>
                    <p><strong>題目:</strong> {{ result.question_text }}</p>
                    <ul>
                        <!-- 給選項重新加上題號 -->
                        {% set labels = ['A', 'B', 'C', 'D'] %}
                        {% for option in result.options %}
                        <li>({{ labels[loop.index0] }}) {{ option }}</li>
                        {% endfor %}
                    </ul>
                </div>
                {% endfor %}
                {% endif %}
            </div>
        </div>
    </div>
</main>

最後測試一下,可以順利搜尋到題目。
https://ithelp.ithome.com.tw/upload/images/20250917/20169370ZqACezTrHx.png


上一篇
DAY2 - 題庫建立
系列文
打造你的數位圖書館:從雜亂檔案到個人化知識庫3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言